package com.itheima.sh.a_axios_json_01;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

@WebServlet("/json4Servlet")
public class Json4Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //需求：请求时json字符串，响应也是json字符串
        /*如果前端请求的数据是json类型，需要借助fastjson工具类api将数据封装到对应的pojo实体类中
        public static final <T> T parseObject(InputStream is, Class<T> clazz);
        Class<T> clazz:实体类class对象
         // 将从页面获取的字节输入流中的字符数据解析成指定类型JavaBean
         注意：
         {“username”:“张三”,"password"：1234}来自前端浏览器
         实体类：
         class User{
         private String username;//这里的成员变量必须和前端提交的json格式的数据key一致，必须使username
         private String password;
         }
         */
        try {
            //获取请求参数
            User  user = JSON.parseObject(request.getInputStream(), User.class);
            //输出控制台
            System.out.println("user = " + user);
            //创建friden集合对象
            ArrayList<Friend> friends = new ArrayList<>();
            Collections.addAll(friends,new Friend("001","张三",123),new Friend("002","李四",456)
                    ,new Friend("003","王五",789));
            //执行到这里说明没有异常，响应给前端
            Result result = new Result(true, "响应好友列表成功", friends);
            //将result转化为json对象
            String resultJson = JSON.toJSONString(result);
            //将result响应给前端浏览器
            response.getWriter().print(resultJson);
        } catch (Exception e) {
            //将异常打印到控制台
            e.printStackTrace();
            //执行到这里说明出现异常
            Result result = new Result(false, "查询好友列表失败");
            //将result转化为json对象
            String strJson = JSON.toJSONString(result);
            //将result响应给浏览器
            response.getWriter().print(strJson);
        }
    }
}